package me.zhyd.braum.spring.boot;

import me.zhyd.braum.spring.boot.annotation.EnableBraumConfiguration;
import me.zhyd.braum.spring.boot.cache.Cache;
import me.zhyd.braum.spring.boot.cache.ConcurrentHashMapCache;
import me.zhyd.braum.spring.boot.cache.RedisCache;
import me.zhyd.braum.spring.boot.property.BraumProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;

/**
 * @author yadong.zhang (yadong.zhang0415(a)gmail.com)
 * @version 1.0
 * @since 1.8
 */
@Configuration
@ConditionalOnBean(annotation = EnableBraumConfiguration.class)
@EnableConfigurationProperties(BraumProperties.class)
public class BraumAutoConfiguration {

    private static final Logger log = LoggerFactory.getLogger(BraumAutoConfiguration.class);

    @Autowired
    BraumProperties properties;

    @PostConstruct
    public void init() {
        log.info("Braum has been turned on! Best wishes for you! ");
        log.info("You'll be safe with braum... ");
    }

    @Bean
    @ConditionalOnMissingBean(name = {"braumProcessor"})
    BraumProcessor BraumProcessor() {
        return new BraumShieldProcessor();
    }

    @Bean(name = "braumCache")
    Cache braumCache() {
        BraumCacheType type = properties.getType();
        if (type == BraumCacheType.REDIS) {
            log.info("Enabling Braum cache: [Redis]");
            return new RedisCache();
        }
        log.info("Enabling Braum cache: [Map]");
        return new ConcurrentHashMapCache();
    }
}
